package com.cloud.message;

import org.apache.commons.lang3.ObjectUtils;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket消息处理类
 *
 * @author yzj
 */
public class WebSocketConsumer {

    private static Logger logger = LoggerFactory.getLogger(WebSocketConsumer.class);

    /**
     * 存储在线WebSocket对象
     */
    public static final Map<String, WebSocketClient> SOCKET_CLIENT = new HashMap<>();

    /**
     * 校验SocketClient对象
     *
     * @param clientId
     * @return client对象不存在返回 true
     */
    public static boolean checkClientExist(String clientId) {
        if (SOCKET_CLIENT.containsKey(clientId)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 设置SocketClient对象
     */
    public static void setSocketClient(String clientId, WebSocketClient socketClient) {
        SOCKET_CLIENT.put(clientId, socketClient);
    }

    /**
     * 移除SocketClient对象
     *
     * @param clientId
     */
    public static void removeSocketClient(String clientId) {
        SOCKET_CLIENT.remove(clientId);
    }

    /**
     * 发送消息内容
     *
     * @param data
     */
    public static void sendMessage(String clientId, Object data) {
        WebSocketClient socketClient = SOCKET_CLIENT.get(clientId);
        if (ObjectUtils.isNotEmpty(socketClient)) {
            // 0为请求中1为已建立/其它值都是建立失败
            if (0 == socketClient.getReadyState().ordinal()) {
                logger.info("[SocketClient消息]连接已断开,请连接后重试.");
            }
            if (1 == socketClient.getReadyState().ordinal()) {
                socketClient.send(String.valueOf(data));
            }
        } else {
            logger.info("[SocketClient消息]发送消息失败,WebSocketClient对象不存在");
        }
    }

}
